<template>
	<view class="page_body">
		<!-- 状态栏高度 设置背景色 占位状态栏-->
		<view style="position: fixed;width:100%;left:0;top:0;z-index: 999;">
			<view class="ztl"
				:style="{'height':statusBarHeights+'px'}"></view>
			<!-- 占位盒子 -->
			<view class=""
				:style="{'height': hieghts+'px'}"></view>
			<!-- 导航栏 -->
			<navBar bgColor="#FFF">
				<image :slot="'left'"
					@click='navToBack'
					:src="xcxImgUrl+'fanhui.svg'"
					style="width: 36rpx;height: 36rpx;"></image>
				<text :slot="'content'">线下支付</text>
			</navBar>
		</view>
		
		<view style="position: relative;" :style="{top:(statusBarHeights+hieghts+'px'),marginTop:-(keyboardHeight)+'px'}">
			<scroll-view
			:style="{'height': 'calc(100vh - ' + statusBarHeights+'px - '+ hieghts +'px)'}"
			scroll-y
			class="mian_offlinePay" >
			
				<view class="mian_offlinePay_top pd10">
					<view class="mian_offlinePay_top_t">
						<image class="mr10" :src="xcxImgUrl+'page_public/static/xianxiafukuanzhanghu.svg'"></image>
						<text>{{accountItem && accountItem.account ? accountItem.account : ''}}</text>
					</view>
					<view class="mian_offlinePay_top_b mt10">
						<view 
						@click="imgShow=true"
						class="mian_offlinePay_top_b_l mr10">
							<image  :src="accountItem && accountItem.url ? uploadImgUrl + accountItem.url : computedMorentu"></image>
						</view>
						<view class="mian_offlinePay_top_b_c ">
							<view class="mian_offlinePay_top_b_c_t textOneShow">
								{{accountItem && accountItem.bank ? accountItem.bank : ''}}
							</view>
							<view class="mian_offlinePay_top_b_c_b textOneShow mt10">
								{{accountItem && accountItem.bankNo ? accountItem.bankNo : ''}}
							</view>
						</view>
						<view 
						v-if="accountList.length > 1" 
						@click="accountShow = true"
						class="mian_offlinePay_top_b_r">
							<image :src="xcxImgUrl+'page_public/static/youjiantou.svg'"></image>
						</view>
					</view>
				</view>
				
				<view class="mian_offlinePay_form pd10 mt10">
					<view class="mian_offlinePay_form_item">
						<view class="">
							订单金额
						</view>
						<view class="">
							￥{{Utils.formatToFixed(yinfuMoney*1,'money')}}
						</view>
					</view>
					<view class="mian_offlinePay_form_item">
						<view class="">
							待付金额
						</view>
						<view class="">
							￥{{Utils.formatToFixed(yinfuMoney*1,'money')}}
						</view>
					</view>
					<view class="mian_offlinePay_form_item_input">
						<view class="mian_offlinePay_form_item_input_l mr10">
							支付流水号
						</view>
						<view class="mian_offlinePay_form_item_input_r">
							<u--input
							ref="a"
							border='none'
							v-model="liushuihao"
							placeholder='请输入流水号'
							maxlength="64"
							>
							</u--input>
						</view>
					</view>
					<view class="mian_offlinePay_form_item_input">
						<view class="mian_offlinePay_form_item_input_l mr10">
							支付日期
						</view>
						<view @click="payTimeShow=true;" class="mian_offlinePay_form_item_input_r">
							<u--input
							border='none'
							placeholder='请选择支付日期'
							suffixIcon="arrow-right"
							v-model="payTime" 
							 readonly
							>
								
							</u--input>
						</view>
					</view>
					<view class="mian_offlinePay_form_item_upload">
						<view class="mtb10">
							支付凭证
						</view>
						<view class="mian_offlinePay_form_item_input_r">
							<image 
							 v-for="(item,index) in FileList"
							 :key="index"
							 style="width: 160rpx;height: 160rpx;margin-right: 20rpx;" 
							 :src="item.url ? uploadImgUrl + item.url : ''"></image>
							<image v-if="FileList.length<3" @click="uploadImg" style="width: 160rpx;height: 160rpx;" :src="xcxImgUrl+'page_public/static/shangchuan.svg'"></image>
						</view>
					</view>
					<view class="mian_offlinePay_form_item_upload" style="position: relative;">
						<view class="mtb10">
							备注信息
						</view>
						<view class="mian_offlinePay_form_item_input_r">
							<u-textarea 
							border='none'
							height="150"
							v-model='remark'
							confirmType='done'
							placeholder="请输入内容"
							@focus="focus"
							@blur="blur"
							></u-textarea>
						</view>
					</view>
				</view>
				
				<view @click="surePay" class="btn">
					<newBtn bgColor="#ec4141" color="#fff" name="确认支付"></newBtn>
				</view>
			</scroll-view>
		</view>
		
		<!-- 日期选择 -->
		<u-datetime-picker
		    :show="payTimeShow"
		    v-model="value1"
		    mode="date"
			@cancel='payTimeShow = false'
			@confirm='sureConfirm'
		></u-datetime-picker>
		
		<!-- 图片保存 -->
		<u-popup
		:show="imgShow"
		:round="30"
		closeable
		@close="imgShow=false"
		>
			<view class="imagePopup">
				<view class="imagePopup_title">
					账户图片
				</view>
				
				<view class="imagePopup_Img">
					<image  :src="accountItem && accountItem.url ? uploadImgUrl + accountItem.url : computedMorentu"></image>
				</view>
				<!-- #ifdef H5 -->
				<view
				class="btn">
					<newBtn bgColor="#ffe3e3" color="#ec4141" name="长按图片保存"></newBtn>
				</view>
				<!-- #endif -->
				
				<!-- #ifndef H5 -->
				<view
				@click="sureImg"
				class="btn">
					<newBtn bgColor="#ffe3e3" color="#ec4141" name="保存图片"></newBtn>
				</view>
				<!-- #endif -->
			</view>
		</u-popup>
		
		<!-- 账户选择 -->
		<u-popup 
		:show="accountShow" 
		:round="30"
		closeable
		@close="accountShow=false" >
		    <view class="accountList">
		        <view class="accountList_title">
		        	账户选择
		        </view>
				<scroll-view
				scroll-y
				class="accountList_scroll pd_lr10"
				>
					<view 
					v-for="(item,index) in accountList"
					:key="index"
					@click="selectAccount(index)"
					class="accountList_item pd10 mt10">
						<view class="accountList_item_l">
							<view class="accountList_item_l_t">
								<image class="mr10" :src="xcxImgUrl+'page_public/static/xianxiafukuanzhanghu.svg'"></image>
								<text>{{item.account ? item.account : ''}} </text>
							</view>
							<view class="accountList_item_l_c mtb10">
								{{item.bank ? item.bank : ''}}
							</view>
							<view class="accountList_item_l_b">
								{{item.bankNo ? item.bankNo : ''}}
							</view>
						</view>
						<view class="accountList_item_r">
							
							<!-- <checkbox
							@click="selectAccount(index)"
							:checked="item.checked"
							color="#ec4141"
							style="transform:scale(0.7);border-radius: 50%;font-weight: bold;background-color: red;"
							></checkbox> -->
								<view class="custom_checkbox">
							<u-checkbox-group 
								@change="selectAccount(index)">
								<u-checkbox :checked="item.checked" :name="true" active-color="red"></u-checkbox>
							</u-checkbox-group>
							</view>
						</view>
					</view>
				</scroll-view>
				
				<view
				 @click="sureAccount"
				 class="srcoll_btm">
					<newBtn bgColor="#ec4141" color="#fff" name="确定"></newBtn>
				</view>
				
		    </view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import newBtn from '@/components/newBtn/newBtn.vue'
	import {uploadImgUrl} from '@/utils/request.js'
	import {createMallOrderMoney,mallOfflinePayment} from '@/api/global.js'
	export default {
		computed:{
			...mapGetters(['demoTopHieght']),
			//返回默认图
			computedMorentu(){
				return this.$store?.state?.morentu
			}
		},
		components:{
			newBtn
		},
		data() {
			return {
				uploadImgUrl,
				statusBarHeight:'',
				hieght:'',
				statusBarHeights:``,
				hieghts:``,
				accountList:[],//账户列表
				accountItem:{},//当前账户
				accountShow:false,//账户列表弹出层
				imgShow:false,//图片弹出层
				payTimeShow:false,//日期弹出层
				value1: Number(new Date()),//当前时间
				yinfuMoney:0,//应付金额
				liushuihao:'',//支付流水号
				payTime:'',//支付日期
				remark:'',//备注
				FileList:[],//支付凭证
				orderId:'',//订单id
				keyboardHeight:0,
			};
		},
		onLoad(options) {
			//保存金额
			this.yinfuMoney = options?.yinfuMoney || 0
			//保存订单id
			this.orderId = options?.orderId || '';
		},
		onShow() {
			this.$nextTick(() => {
				// 获取状态栏的高度
				this.statusBarHeight = this.$store.state.statusBarHeight * 2 + 'rpx'
				this.statusBarHeights = this.$store.state.statusBarHeight;
				// 计算站位的高度
				this.hieght = (this.$store.state.navBarHeight) * 2 + 'rpx'
				this.hieghts = (this.$store.state.navBarHeight);
				//获取高度
				this.Utils.getDemoTopHeight('mian_offlinePay')
				
				//获取账户列表
				this.getList()
				console.log(this.accountItem);
			})
		},
		methods:{
			focus(e){
				console.log(e.detail.height,890)
				this.keyboardHeight = e.detail.height;
			},
			blur(){
				this.keyboardHeight = 0;
			},
			//确认
			async surePay(){
				//先校验必填
				if(this.accountItem && !this.accountItem.account){
					this.Utils.toast('请设置支付账户');
					return
				}
				if(this.liushuihao == ''){
					this.Utils.toast('请填写支付流水号')
					return
				}
				if(this.payTime == ''){
					this.Utils.toast('请选择支付日期')
					return
				}
				
				
				//生成支付记录
				let res = await createMallOrderMoney({
					payType:4,//支付类型【1:微信支付 2:通联支付 3:富友支付 4:线下支付 5:挂账支付】
					money:this.yinfuMoney,
					subjectId:this.accountItem?.subjectId || '',//会计科目id[关联会计科目表]
					orderId:this.orderId,//订单id
				})
				//生成支付记录成功
				if(res.code == 2000){
					
					//调用线下支付接口
					let resP = await mallOfflinePayment({
						moneyId:res?.data?.code || '',//订单收款id
						trueMoney:this.yinfuMoney,//真实交易金额
						subjectId:this.accountItem?.subjectId || '',
						payNumber:this.liushuihao,//交易流水号
						fileUrl3:this.FileList && this.FileList.length && this.FileList[2] ? this.uploadImgUrl + this.FileList[2].url : '',
						fileUrl2:this.FileList && this.FileList.length && this.FileList[1] ? this.uploadImgUrl + this.FileList[1].url : '',
						fileUrl1:this.FileList && this.FileList.length && this.FileList[0] ? this.uploadImgUrl + this.FileList[0].url : '',
						summary:this.remark,
						accountName:this?.accountItem?.account || '',//线下收款账户
						bank:this?.accountItem?.bank || '',//开户行
						bankNo:this?.accountItem?.bankNo || '',//银行卡号
						payTime:this.payTime
					})
					if(resP.code == 2000){
						uni.navigateTo({
							url:'/page_public/successPay'
						})
					}else{
						this.Utils.toast(`${resP.msg}`);
					}
					
				}else{
					this.Utils.toast(`${res.msg}`);
				}
				
				
			},
			//保存图片
			sureImg(){
				// #ifdef APP-PLUS
				uni.saveImageToPhotosAlbum({
					filePath:this.uploadImgUrl + this.accountItem.url,
					success:()=> {
						this.Utils.toast('保存成功')
					}
				})
				// #endif
				// #ifdef H5
						let Url = this.uploadImgUrl + this.accountItem.url; //图片路径，也可以传值进来
						var triggerEvent = "touchstart"; //指定下载方式
					    var blob=new Blob([''], {type:'application/octet-stream'}); //二进制大型对象blob
					    var url = URL.createObjectURL(blob); //创建一个字符串路径空位
					    var a = document.createElement('a'); //创建一个 a 标签
					    a.href = Url;  //把路径赋到a标签的href上
					    //正则表达式，这里是把图片文件名分离出来。拿到文件名赋到a.download,作为文件名来使用文本
					    a.download = Url.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0]; 
					    /* var e = document.createEvent('MouseEvents');  //创建事件（MouseEvents鼠标事件）
					    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); //初始化鼠标事件（initMouseEvent已弃用）*/
					    
					    //代替方法。创建鼠标事件并初始化（后面这些参数我也不清楚，参考文档吧 https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent）
						var e = new MouseEvent('click', ( true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null));  
						//派遣后，它将不再执行任何操作。执行保存到本地
					    a.dispatchEvent(e); 
					    //释放一个已经存在的路径（有创建createObjectURL就要释放revokeObjectURL）
					    URL.revokeObjectURL(url);  
						/* 
						//这段好像并不影响，所以我不用，注释掉
						var imgs = document.getElementsByTagName("img");
						for(var i = 0,o;o = imgs[i];i++){
							
							o.addEventListener(triggerEvent,function(){
								var newurl = this.getAttribute("src");
								saveAs(newurl);
							},false);
						} */
				
				// #endif
				
			},
			//上传凭证
			async uploadImg(){
				//唤起选择图片
				let bdImgUrl =  await this.Utils.takeAPhoto(['album','camera'])
				console.log(bdImgUrl);
				if(bdImgUrl.tempFilePaths.length>1){
					this.Utils.toast('单次只允许上传一张图片')
					return
				}
				//上传服务器
				let res = await this.Utils.uploadFilePromise(bdImgUrl.tempFilePaths[0])
				console.log(res);
				if(res.code == 2000){
					this.FileList.push(res?.data?.info?.[0])
				}else{
					this.Utils.toast('上传失败')
				}
			},
			//时间确认
			sureConfirm(value){
				console.log(value);
				this.payTime =  this.Utils.DateFormateTime(value.value,'nyr')
				this.payTimeShow = false
			},
			//返回上一级
			navToBack(){
				uni.navigateBack()
			},
			//获取账户列表
			getList(){
				this.accountList = JSON.parse(this.$store?.state?.configSetting?.xianxiaPay)
				this.accountList = this.accountList.length ? this.accountList.map(item=>{
					return {
						...item,
						checked:false
					}
				}) : []
				this.accountItem = this.accountList && this.accountList.length ? this.accountList[0] : {}
			},
			//选择账户
			selectAccount(index){
				console.log(index)

				this.$set(this.accountList[index], 'checked', !this.accountList[index].checked )
				this.accountList.forEach((item,inx)=>{
					if(index != inx){

						this.$set(this.accountList[inx], 'checked', false )
					}
				})
				console.log(this.accountList)
			},
			//选择账户确认
			sureAccount(){
				this.accountItem = this.accountList.filter(item=>item.checked)[0]
				this.accountShow = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-input__content__subfix-icon {
		 margin-left: 130rpx !important;
		
	}
	/deep/.u-icon__icon {
				font-size: 24rpx !important;
	}
	/deep/ .u-popup__content__close{
	top: 22rpx;
	 height: 36rpx;
	 width: 36rpx;
	 line-height: 80rpx;
	 border: rgb(144, 147, 153) 1px solid;
	border-radius: 50%;
	 display: flex;
	 align-items: center;
	 justify-content: center;
	}
.mian_offlinePay{
	width: 100%;
	box-sizing: border-box;
	padding-bottom: 120rpx;
	min-height:50vh;
	overflow: hidden auto;
	.mian_offlinePay_top{
		width: 100%;
		height: 260rpx;
		background-color: #FFF;
		box-sizing: border-box;
		.mian_offlinePay_top_t{
			height: 60rpx;
			display: flex;
			align-items: center;
			image{
				width: 36rpx;
				height: 36rpx;
			}
			text{
				font-size: $font_size_14;
				font-weight: bold;
				color: $text_color_333;
			}
		}
		.mian_offlinePay_top_b{
			display: flex;
			align-items: center;
			.mian_offlinePay_top_b_l{
				width: 120rpx;
				height: 120rpx;
				image{
					width: 100%;
					height: 100%;
				}
			}
			.mian_offlinePay_top_b_c{
			  width:300rpx;
				.mian_offlinePay_top_b_c_t{
					font-weight: bold;
					font-size: 32rpx;
					color: $text_color_333;
				}
				.mian_offlinePay_top_b_c_b{
					font-size: $font_size_14;
					color: $text_color_333;
				}
			}
			.mian_offlinePay_top_b_r{
				width: 24rpx;
				height:24rpx;
				margin-left: 110px;
				image{
					width: 100%;
					height: 100%;
				}
			}
		}
	}
	
	.mian_offlinePay_form{
		width: 100%;
		background-color: #FFF;
		box-sizing: border-box;
		font-size: $font_size_14;
		color: $text_color_333;
		.mian_offlinePay_form_item{
			height: 88rpx;
			border-bottom: 1px solid #f3f3f3;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.mian_offlinePay_form_item_input{
			height: 88rpx;
			border-bottom: 1px solid #f3f3f3;
			display: flex;
			align-items: center;
			.mian_offlinePay_form_item_input_l{
				width: 170rpx;
			}
			.mian_offlinePay_form_item_input_r{
				
				u--input{
					width: 100%;
				}
			}
		}
	}
}

.btn{
	width: 100%;
	position: fixed;
	left: 0;
	bottom: 40rpx;
}

.accountList{
	width: 100%;
	height: calc(100vh - 30vh);
	.accountList_title{
		height: 88rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: $font_size_18;
		color: $text_color_333;
		font-weight: bold;
	}
	.accountList_scroll{
		height:calc(100vh - 30vh - 88rpx) ;
		box-sizing: border-box;
		padding-bottom: 120rpx;
		.accountList_item{
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-radius: $border_radius_10;
			border: 1px solid #f3f3f3;
			
			.accountList_item_l{
				.accountList_item_l_t{
					height: 60rpx;
					display: flex;
					align-items: center;
					image{
						width: 36rpx;
						height: 36rpx;
					}
					text{
						font-size: $font_size_14;
						color: $text_color_333;
						font-weight: bold;
					}
				}
				.accountList_item_l_c{
					font-size: 32rpx;
					color: $text_color_333;
					font-weight: bold;
				}
				.accountList_item_l_b{
					font-size: $font_size_14;
					color: $text_color_333;
				}
			}
		}
	}
	.srcoll_btm{
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 40rpx;
	}
}

.imagePopup{
	width: 100%;
	height: calc(100vh - 40vh);
	.imagePopup_title{
		height: 88rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: $font_size_18;
		color: $text_color_333;
		font-weight: bold;
	}
	.imagePopup_Img{
		width: 100%;
		text-align: center;
		margin-top: 40rpx;
		image{
			width: 364rpx;
			height: 364rpx;
		}
	}
}
 /deep/.uni-checkbox-input-checked {
				    background-color: red !important;
				    color: #fff !important;
					font-weight: bold;
			}
</style>
